package com.shujia.day15;

public class Code06ThreadLock {
    public static void main(String[] args) {
        /*
            Java中锁的方式：
                synchronized
                    1、修饰代码块
                    2、修饰方法
                        修饰静态方法: 对当前方法定义的类进行做加锁操作，方法执行结束后，释放类的锁
                        修饰成员方法: 对于成员方法进行修饰后，那么当前对象执行过程中会被加锁，当方法执行结束后，那么会将锁进行释放 供其他的线程使用
         */
        LockNum lockNum = new LockNum();  // 该对象只有一个

        ThreadLock1 threadLock1 = new ThreadLock1(lockNum);   // 自定义线程类 有两个
        ThreadLock1 threadLock2 = new ThreadLock1(lockNum);

        Thread thread = new Thread(threadLock1, "1号");
        Thread thread1 = new Thread(threadLock2, "2号");

        thread.start();
        thread1.start();

    }
}

class ThreadLock1 implements Runnable {

    LockNum lockNum;

    public ThreadLock1(LockNum lockNum) {
        this.lockNum = lockNum;
    }

    @Override
    public void run() {
        fun(lockNum);
    }

    public synchronized static void fun(LockNum lockNum) {
        for (int i = 0; i < 1000; i++) {
            try {
                Thread.sleep(50);
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
            lockNum.num += 1;
            System.out.println(Thread.currentThread().getName() + "累加结果"+lockNum.num);
        }

    }

}


class LockNum {
    int num = 0;
}